/**
 * ChatContext - 提供全局聊天状态管理
 * 包含所有对话历史、当前会话和消息处理方法
 */
import React, { createContext, useContext, useState, useEffect } from 'react';
import { v4 as uuidv4 } from 'uuid';
import toast from 'react-hot-toast';
import { type ChatMessage, type Conversation } from '../model/Message';


interface ChatContextType {
    conversations: Conversation[];
    currentConversation: Conversation | null;
    isLoading: boolean;
    sendMessage: (content: string) => Promise<void>;
    createNewConversation: () => void;
    selectConversation: (id: string) => void;
    clearConversation: () => void;
    deleteConversation: (id: string) => void;
}

const ChatContext = createContext<ChatContextType | undefined>(undefined);

export const useChatContext = () => {
    const context = useContext(ChatContext);
    if (!context) {
        throw new Error('useChatContext must be used within a ChatProvider');
    }
    return context;
};

export const ChatProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [conversations, setConversations] = useState<Conversation[]>([]);
    const [currentConversation, setCurrentConversation] = useState<Conversation | null>(null);
    const [isLoading, setIsLoading] = useState(false);

    // 初始化默认会话
    useEffect(() => {
        if (conversations.length === 0) {
            const defaultConversation: Conversation = {
                id: uuidv4(),
                title: '新对话',
                messages: [],
                createdAt: new Date().toISOString(),
            };

            setConversations([defaultConversation]);
            setCurrentConversation(defaultConversation);
        }
    }, []);

    // 模拟 AI 响应
    const simulateAIResponse = async (userMessage: string): Promise<string> => {
        // 简单的回复生成逻辑，实际项目中应连接后端 API
        const responses = [
            `我理解你的问题是关于"${userMessage.substring(0, 20)}${userMessage.length > 20 ? '...' : ''}"。这是一个很好的问题！`,
            `对于"${userMessage.substring(0, 20)}${userMessage.length > 20 ? '...' : ''}"，我的回答是：这取决于具体情况，但一般来说...`,
            `你问的是"${userMessage.substring(0, 20)}${userMessage.length > 20 ? '...' : ''}"，让我来解释一下：`,
            `关于"${userMessage.substring(0, 20)}${userMessage.length > 20 ? '...' : ''}"，有几点需要考虑：\n\n1. 首先...\n2. 其次...\n3. 最后...`,
            `"${userMessage.substring(0, 20)}${userMessage.length > 20 ? '...' : ''}"是一个复杂的主题，让我从以下几个方面分析：\n\n## 基础概念\n...\n\n## 应用场景\n...\n\n## 最佳实践\n...`
        ];

        // 随机选择一个回复
        const randomResponse = responses[Math.floor(Math.random() * responses.length)];

        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 2000));

        return randomResponse;
    };

    const sendMessage = async (content: string) => {
        if (!content.trim() || !currentConversation) return;

        // 创建用户消息
        const userMessage: ChatMessage = {
            id: uuidv4(),
            role: 'user',
            content,
            timestamp: new Date().toISOString(),
        };

        // 更新对话
        const updatedConversation = {
            ...currentConversation,
            messages: [...currentConversation.messages, userMessage],
        };

        setCurrentConversation(updatedConversation);
        setConversations(prev =>
            prev.map(conv => conv.id === updatedConversation.id ? updatedConversation : conv)
        );

        // 开始加载
        setIsLoading(true);

        try {
            // 获取 AI 响应
            const aiResponseContent = await simulateAIResponse(content);

            // 创建 AI 消息
            const aiMessage: ChatMessage = {
                id: uuidv4(),
                role: 'assistant',
                content: aiResponseContent,
                timestamp: new Date().toISOString(),
            };

            // 更新对话包含 AI 响应
            const finalConversation = {
                ...updatedConversation,
                messages: [...updatedConversation.messages, aiMessage],
                // 如果是第一条消息，更新对话标题
                title: updatedConversation.messages.length === 1 ? content.substring(0, 30) : updatedConversation.title,
            };

            setCurrentConversation(finalConversation);
            setConversations(prev =>
                prev.map(conv => conv.id === finalConversation.id ? finalConversation : conv)
            );
        } catch (error) {
            toast.error('获取回复失败，请重试');
            console.error('Failed to get AI response:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const createNewConversation = () => {
        const newConversation: Conversation = {
            id: uuidv4(),
            title: '新对话',
            messages: [],
            createdAt: new Date().toISOString(),
        };

        setConversations(prev => [newConversation, ...prev]);
        setCurrentConversation(newConversation);
    };

    const selectConversation = (id: string) => {
        const conversation = conversations.find(conv => conv.id === id);
        if (conversation) {
            setCurrentConversation(conversation);
        }
    };

    const clearConversation = () => {
        if (!currentConversation) return;

        const clearedConversation = {
            ...currentConversation,
            messages: [],
        };

        setCurrentConversation(clearedConversation);
        setConversations(prev =>
            prev.map(conv => conv.id === clearedConversation.id ? clearedConversation : conv)
        );

        toast.success('对话已清空');
    };

    const deleteConversation = (id: string) => {
        setConversations(prev => prev.filter(conv => conv.id !== id));

        if (currentConversation && currentConversation.id === id) {
            // 删除当前对话后，选择第一个对话，如果没有对话则创建新对话
            if (conversations.length > 1) {
                const nextConversation = conversations.find(conv => conv.id !== id);
                setCurrentConversation(nextConversation || null);
            } else {
                createNewConversation();
            }
        }

        toast.success('对话已删除');
    };

    const value = {
        conversations,
        currentConversation,
        isLoading,
        sendMessage,
        createNewConversation,
        selectConversation,
        clearConversation,
        deleteConversation,
    };

    return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;
};
